package com.itany.corejava.code13_jdbc;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author MissChen
 * @version 1.0
 * @date 2023 年12月11日 16:38
 */
public class JDBCUtil {
    private static Properties p;

    static {
        p = new Properties();
        try {
            p.load(JDBCUtil.class.getClassLoader().getResourceAsStream("dataSource.properties"));

        } catch (IOException e) {
            e.printStackTrace();
            //静态代码块中出现异常，使用的JDK提供的ExceptionInInitializerError
            throw new ExceptionInInitializerError("JDBCUtil初始化失败");
        }
    }

    public static Connection getConnection() throws DataAccessException {
        Connection conn = null;
        try {
            //注册驱动
            Class.forName(p.getProperty("driverClassName"));
            conn = DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"), p.getProperty("password"));

        } catch (ClassNotFoundException e) {
            // System.out.println("未找到驱动");
            // e.printStackTrace();
            throw new DataAccessException("未找到驱动");

        } catch (SQLException e) {
            // System.out.println("数据库访问异常");
            // e.printStackTrace();
            throw new DataAccessException("数据库访问异常");
        }
        return conn;
    }

    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) throws DataAccessException {
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {

                throw new DataAccessException("释放结果集出错");
            }
        }
        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                throw new DataAccessException("释放状态集出错");
            }
        }
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new DataAccessException("释放结果集出错");
            }
        }
    }


}
